<template>
  <div class="permission-resource">
    <a-card :bordered="false">
      <div class="toolbar">
        <c-table-search-form
          v-model="tableSearchForm"
          :datas="tableSearchFormData"
          @onSearch="onSearch"
          @onAdd="onAdd('', 'add')"
        >
          <template slot="startPermissionBtn">
            <a-popconfirm
              :title="`是否启动权限？`"
              ok-text="确定"
              cancel-text="取消"
              @confirm="onStartPermissions"
            >
              <a-button class="bgGreen" icon="play-circle">启动权限</a-button>
            </a-popconfirm>
          </template>
          <template slot="allDeleteBtn">
            <a-popconfirm
              :title="`是否确认删除所勾选的权限?`"
              v-if="selectedRowKeys.length > 0"
              ok-text="确定"
              cancel-text="取消"
              @confirm="onDeleteAll"
            >
              <a-button icon="delete" type="danger">批量删除</a-button>
            </a-popconfirm>
          </template>
        </c-table-search-form>
      </div>
      <c-table
        v-if="gridOptions.data.length == 0"
        :datas="gridOptions.data"
        rowSelection
        :columns="gridOptions.columns"
        :loading="loading"
      ></c-table>

      <vxe-grid
        v-else
        :tree-config="{  children: 'children' ,trigger: 'row', highlight: true }"
        highlight-hover-row
        @checkbox-change="selectChangeEvent"
        @checkbox-all="selectAllEvent"
        ref="resourcexGrid"
        v-bind="gridOptions"
      >
        <!-- 菜单名称 -->
        <template #resourceName="{ row }">
          <a-tooltip :title="row.resourceName" arrow-point-at-center>
            <span class="cursor-pointer">{{ row.resourceName }}</span>
          </a-tooltip>
        </template>
        <!-- 资源url -->
        <template #url="{ row }">
          <a-tooltip :title="row.url" arrow-point-at-center>
            <span class="cursor-pointer">{{ row.url }}</span>
          </a-tooltip>
        </template>
        <!-- 菜单类型 -->
        <template #type="{ row }">
          <a-tag :color="$dealDic(menuType,row.type,'tagColor')">
            {{$dealDic(menuType,row.type,'label')}}
          </a-tag>
        </template>
        <!-- 菜单状态 -->
        <template #resourceState="{ row }">
          <a-tag :color="$dealDic(menuStatus,row.resourceState,'tagColor')">
           {{$dealDic(menuStatus,row.resourceState,'label')}}
          </a-tag>
        </template>
        <!-- 图标 -->
        <template #icon="{ row }">
          <Icon
            class="table-list-icon"
            :iconStyle="iconStyle"
            :type="row.icon"
          />
        </template>
        <!-- 创建时间 -->
        <template #createDate="{ row }">
          <span>{{ $getTime(row.createDate) }}</span>
        </template>
        <!-- 表格操作 -->
        <template #operate="{ row }">
          <!-- 启动、停止权限 -->
          <div class="display-inline">
            <a-popconfirm
              :title="
                `是否${row.resourceState === 0 ? '启动' : '停止'}该权限资?`
              "
              ok-text="确定"
              cancel-text="取消"
              @confirm="onStartStatus(row)"
            >
              <a @click.stop="" :class="row.resourceState === 0 ? '' : 'stop'">
                <Icon
                  v-if="row.resourceState === 0"
                  :iconStyle="startIconStyle"
                  :type="'zk-back-start'"
                />
                <a-icon v-else type="stop" />
                {{ row.resourceState === 0 ? "启动" : "停止" }}
              </a>
            </a-popconfirm>
          </div>
          <!-- 编辑 -->
          <div class="display-inline">
            <a-divider type="vertical" />
            <a @click.stop="onEdit(row)"> <a-icon type="edit" />编辑 </a>
          </div>
          <!-- 删除 -->
          <div class="display-inline">
            <a-divider type="vertical" />
            <a-popconfirm
              :title="`是否确认删除该权限资源管理?`"
              ok-text="确定"
              cancel-text="取消"
              @confirm="onDel([row.id])"
            >
              <a @click.stop=""> <a-icon type="delete" />删除 </a>
            </a-popconfirm>
          </div>
        </template>
      </vxe-grid>
    </a-card>
    <a-drawer
      :title="handleType == 'add' ? '新增权限资源' : '编辑权限资源'"
      :width="'30%'"
      :visible="visible"
      @ok="onOk"
      @cancel="onCancel"
      :destroyOnClose="true"
      @close="onCancel"
    >
      <c-form-model
        class="margin-b70"
        :datas="formData"
        v-model="form"
        :rules="rules"
        ref="formModels"
      >
        <!-- formModel自定义部分 -->
        <a-input
          slot="icon"
          allow-clear
          v-model="form.icon"
          placeholder="请输入菜单图标"
          @click="openMenuIconSelector"
        ></a-input>
        <a-radio-group
          slot="type"
          slot-scope="row"
          v-model="form[row.tableRow.prop]"
        >
          <a-radio
            v-for="(item, index) in menuType"
            :key="index"
            :value="item.value"
            >{{ item.label }}</a-radio
          >
        </a-radio-group>

        <a-switch
          slot="hidden"
          size="small"
          v-model="form.hidden"
          default-checked
        />
      </c-form-model>
      <div class="drawer-footer-btn flex-center">
        <a-button class="margin-r10" @click="onCancel">取消</a-button>
        <a-button type="primary" :loading="confirmLoading" @click="onOk"
          >确定</a-button
        >
      </div>
    </a-drawer>

    <a-modal
      width="35%"
      v-model="menuIconVisible"
      :zIndex="zIndex"
      :footer="null"
      title="请选择菜单图标"
    >
      <icon-selector
        v-model="currentSelectedIcon"
        @change="onIconChange"
      ></icon-selector>
    </a-modal>
  </div>
</template>
<script>
import {
  getResourceList,
  deleteResourceList,
  addResourceList,
  updateResourceList,
  refreshAuthdata,
  updateBaseresource
} from "@/api/mallSystem/permissionResource";
import {
  refactoringArr,
  findChildIdArr,
  getIds,
  addTreeAddDisabled
} from "@/util/common";
import IconSelector from "@/components/IconSelector";
import { menuStatus, menuType } from "@/dict/system";
import { businessDirection } from "@/dict/public";

const rules = {
  resourceName: [
    { required: true, message: "请输入权限名称", trigger: "change" }
  ],
  // flag: [{ required: true, message: "请输入前端标识", trigger: "change" }],
  // orderNum: [{ required: true, message: "请输入排序", trigger: "change" }],
  // webOrderNum: [{ required: true, message: "请输入路由排序", trigger: "change" }],
  type: [ { required: true, message: "请输入类型", trigger: "blur" } ]
  // moduleUrl: [{ required: true, message: "请输入组件URL", trigger: "blur" }],
  // path: [{ required: true, message: "请输入前端URL", trigger: "blur" }]
};

const columns = [
  {
    type: "checkbox",
    width: 50,
    fixed: "left"
  },
  {
    field: "resourceName",
    title: "菜单名称",
    showOverflow: true,
    treeNode: true,
    align: "left",
    slots: { default: "resourceName" },
    width: 220,
    fixed: "left"
  },
  { field: "flag", title: "前端标识", width: 180 },
  { field: "type", title: "菜单类型", width: 120, slots: { default: "type" } },
  {
    field: "resourceState",
    title: "菜单状态",
    width: 120,
    slots: { default: "resourceState" }
  },
  { field: "icon", title: "菜单图标", slots: { default: "icon" }, width: 80 },
  {
    field: "url",
    title: "资源URL",
    showOverflow: true,
    width: 300,
    slots: { default: "url" }
  },
  {
    field: "createDate",
    title: "创建时间",
    slots: { default: "createDate" },
    width: 180
  },
  { title: "操作", width: 220, slots: { default: "operate" }, fixed: "right" }
];
const tableSearchFormData = [
  {
    label: "请输入菜单名称",
    prop: "searchKey",
    type: "search"
  },
  {
    prop: "addBtn",
    type: "addBtn"
  },
  {
    prop: "startPermissionBtn",
    type: "slot"
  },
  {
    prop: "allDeleteBtn",
    type: "slot"
  }
];

export default {
  name: "PermissionResource",
  components: {
    IconSelector
  },
  data() {
    return {
      menuType, //菜单类型
      menuStatus, // 菜单状态
      businessDirection, // 业务方向
      rules, //form规则
      columns, //表头信息
      tableSearchFormData,
      loading: false, //表格loading
      menuIconVisible: false, //图标弹窗是否显示
      handleType: "add", //弹窗打开方式
      zIndex: 2000, //弹窗打开方式
      startIconStyle: {
        fontSize: "14px",
        color: "#758cff"
      }, //图标的样式
      iconStyle: {
        fontSize: "18px"
      },
      selectedRowKeys: [],
      selectedRows: [],
      tableSearchForm: {
        searchKey: ""
      },
      confirmLoading: false,
      visible: false,
      currentSelectedIcon: "",
      form: this.initializationParameter(),
      gridOptions: {
        border: true,
        align: "center",
        loading: false,
        columns: columns,
        data: []
      }
    };
  },
  computed: {
    formData() {
      let res = [
        {
          label: "上级路由菜单",
          prop: "webParentId",
          type: "tree-select",
          typeData: this.higherMenu
        },
        {
          label: "上级菜单",
          prop: "parentId",
          type: "tree-select",
          typeData: this.higherMenu
        },
        {
          label: "菜单名称",
          prop: "resourceName"
        },
        {
          label: "菜单类型",
          prop: "type",
          type: "slot"
        },
        {
          label: "前端标识",
          prop: "flag"
        },
        {
          label: "方向标识",
          prop: "resourceDirection",
          type: "select",
          typeData: [ {
              label: "公共",
              value: 0
            } ].concat(businessDirection)
        },
        {
          label: "资源URL",
          prop: "url",
          placeholder: "请输入资源URL（后台没有对应请求资源则默认为空）"
        },
        {
          label: "组件URL",
          prop: "moduleUrl",
          hidden: this.form.type === 1 || this.form.type === 3 ? true : false
        },
        {
          label: "前端URL",
          prop: "path",
          hidden: this.form.type === 1 || this.form.type === 3 ? true : false
        },
        {
          label: "重定向URL",
          prop: "redirect",
          hidden: this.form.type === 1 || this.form.type === 3 ? true : false
        },
        {
          label: "所属菜单",
          prop: "affiliation",
          hidden: this.form.type === 1 || this.form.type === 3 ? true : false
        },
        {
          label: "图标",
          prop: "icon",
          type: "slot"
        },
        {
          label: "排序",
          prop: "orderNum",
          type: "number"
        },
        {
          label: "路由排序",
          prop: "webOrderNum",
          type: "number"
        },
        {
          label: "显隐",
          prop: "hidden",
          type: "slot"
        },
        {
          label: "备注",
          prop: "remark",
          type: "textarea"
        }
      ];
      return res;
    }
  },
  created() {
    this.onPageOnlod();
  },
  methods: {
    openMenuIconSelector() {
      this.menuIconVisible = true;
    },
    initializationParameter() {
      return {
        resourceDirection: 0,
        parentId: undefined,
        webParentId: undefined,
        flag: "",
        id: "",
        orderNum: 1,
        webOrderNum: 1,
        resourceName: "",
        type: 0,
        url: "",
        moduleUrl: "",
        redirect: "",
        affiliation: "",
        icon: "",
        path: "",
        hidden: true //显隐
      };
    },
    //新增操作
    onAdd() {
      this.form = this.initializationParameter();
      addTreeAddDisabled(this.higherMenu, "", "disabled");
      this.selectedRowKeys = [];
      this.selectedRows = [];
      this.handleType = "add";
      this.visible = true;
    },
    //搜索页面
    onSearch() {
      this.onPageOnlod();
    },
    // 初始化页面
    onPageOnlod() {
      this.loading = true;
      getResourceList({
        resourceName: this.tableSearchForm.searchKey.trim()
      }).then(res => {
        if (!res.data) res.data = [];
        if (!this.tableSearchForm.searchKey) {
          this.higherMenu = refactoringArr(
            res.data,
            item => {
              return {
                id: item.id,
                key: item.id,
                parentId: item.parentId,
                value: item.id,
                title: item.resourceName,
                type: item.type
              };
            },
            0
          );
        }
        this.loading = false;
        this.gridOptions.data = refactoringArr(res.data, "", 0);
        // console.log(" this.gridOptions.data==", this.gridOptions.data);
      });
    },

    selectAllEvent({ checked, records }) {
      this.selectedRows = records;
      this.selectedRowKeys = getIds(records, "id");
    },
    selectChangeEvent({ checked, records }) {
      this.selectedRowKeys = records;
      this.selectedRowKeys = getIds(records, "id");
    },
    toggleExpandChangeEvent() {},

    //新增、编辑提交
    onOk() {
      const that = this;
      let onFun;
      that.handleType === "add"
        ? (onFun = addResourceList)
        : (onFun = updateResourceList);
      this.$refs.formModels.handleValidate().then(data => {
        that.confirmLoading = true;
        if (data.parentId == undefined) data = { ...data, parentId: "0" };
        if (data.webParentId == undefined) data = { ...data, webParentId: "0" };
        data.hidden
          ? (data = { ...data, hidden: 0 })
          : (data = { ...data, hidden: 1 });
        onFun(data)
          .then(res => {
            that.$message.success("操作成功");
            that.onPageOnlod();
            that.selectedRowKeys = [];
            that.selectedRows = [];
            that.confirmLoading = false;
            that.visible = false;
          })
          .catch(() => {
            this.confirmLoading = false;
          });
      });
    },
    //编辑
    onEdit(row) {
      addTreeAddDisabled(this.higherMenu, row.id, "disabled", true);
      this.form = JSON.parse(JSON.stringify(row));
      row.parentId === 0
        ? (this.form["parentId"] = undefined)
        : this.form["parentId"];
      row.webParentId === 0
        ? (this.form["webParentId"] = undefined)
        : this.form["webParentId"];
      row.hidden === 0 || row.hidden === "0"
        ? (this.form["hidden"] = true)
        : (this.form["hidden"] = false);
      this.handleType = "edit";
      this.visible = true;
    },
    onDel(idArr) {
      let result = [];
      idArr.map(itemId => {
        result.push(...findChildIdArr(this.gridOptions.data, itemId));
      });
      this.delRequest(result);
    },
    delRequest(result) {
      deleteResourceList(result).then(res => {
        this.$message.success("操作成功");
        this.selectedRowKeys = [];
        this.selectedRows = [];
        this.onPageOnlod();
      });
    },
    //图标change
    onIconChange(icon) {
      this.form.icon = icon;
      this.menuIconVisible = false;
    },
    //开启权限资源（表格内操作）
    onStartStatus(row) {
      let resourceState ;
      let result = [];
      row.resourceState == 0 ? resourceState = 1 : resourceState = 0
      result.push(...findChildIdArr(this.gridOptions.data, row.id));
      updateBaseresource({
        ids: result,
        resourceState: resourceState
      }).then(() => {
        this.$message.success("操作成功");
        row.resourceState = resourceState; // 不刷新页面改变操作按钮当前状态（展开不用合起来）
        // this.onPageOnlod();
      });
    },
    //开启权限资源
    onStartPermissions() {
      refreshAuthdata().then(() => {
        this.$message.success("启动成功");
        this.onPageOnlod();
      });
    },
    //取消
    onCancel(row) {
      this.visible = false;
    },
    //删除所有勾选的项
    onDeleteAll() {
      this.delRequest(this.selectedRowKeys);
    }
  }
};
</script>
<style lang="scss" scoped>
.permission-resource {
  .stop {
    color: #606266;
  }
  .display-inline a {
    font-size: 12px !important;
  }
}
</style>